<template>
  <div class="followAdd" v-loading="detailInfoShow">
    <div class="content" v-if="pageType !== 'detail'">
      <div class="content-title">{{ rowdata.projectName }}</div>
      <div class="content-number">
        <div class="title">项目编号：</div>
        <div class="number">{{ rowdata.projectCode }}</div>
      </div>
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item
        name="1"
        v-if="pageType !== 'detail' && pageType !== 'check'"
        disabled
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">添加跟进信息</span>
        </template>
        <div class="follow-info">
          <el-form
            :model="followForm"
            ref="followFormRef"
            :rules="queryRules"
            label-width="100px"
            v-enterToNext
            :disabled="pageType === 'detail'"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="跟进时间："
                  label-width="120"
                  prop="followTime"
                >
                  <el-date-picker
                    v-model="followForm.followTime"
                    format="YYYY/MM/DD"
                    class="search-input"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="请选择"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item
                  label="跟进内容："
                  prop="content"
                  label-width="120"
                >
                  <el-input
                    style="width: 100%"
                    v-model="followForm.content"
                    type="textarea"
                    maxlength="500"
                    class="custom-textarea"
                    placeholder="请输入内容"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-col :span="12">
              <el-form-item
                label="下次跟进时间："
                prop="nextFollowTime"
                label-width="120"
              >
                <el-date-picker
                  ref="refInput"
                  v-model="followForm.nextFollowTime"
                  format="YYYY/MM/DD"
                  class="search-input"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder="请选择"
                  :popper-options="{ placement: 'right-end' }"
                />
              </el-form-item>
            </el-col>
          </el-form>
        </div>
      </el-collapse-item>
      <!-- 跟进记录 -->
      <el-collapse-item
        name="2"
        v-if="pageType == 'detail' || pageType == 'check'"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">跟进记录</span>
        </template>
        <div class="follow-detail-info">
          <!-- 表格数据 -->
          <el-table
            :data="followForm.tableData"
            border
            height="100%"
            :header-cell-style="{ background: 'red' }"
          >
            <el-table-column
              label="跟进时间"
              prop="createTime"
              :show-overflow-tooltip="true"
              width="120"
              align="center"
            />
            <el-table-column
              label="跟进内容"
              prop="content"
              :show-overflow-tooltip="true"
              min-width="160"
              align="center"
            />
            <el-table-column
              label="下次跟进时间"
              prop="nextFollowTime"
              :show-overflow-tooltip="true"
              min-width="160"
              align="center"
            />
            <el-table-column
              label="操作"
              :show-overflow-tooltip="true"
              :width="'100px'"
            >
              <template #default="{ row }">
                <div class="table-operate">
                  <span @click="handlerdetail(row)" style="cursor: pointer"
                    >查看</span
                  ><span class="line"></span>
                  <span style="cursor: pointer" @click="handleredit(row)"
                    >编辑</span
                  >
                </div>
              </template></el-table-column
            >
          </el-table>
        </div>
      </el-collapse-item>
    </el-collapse>
    <!-- 筛选按钮 -->
    <div v-if="pageType !== 'detail' && pageType !== 'check'" class="allbutton">
      <el-button
        type="primary"
        v-if="pageType !== 'detail' && pageType !== 'check'"
        class="btn save"
        @click="handleAddSave(followFormRef)"
        >确认</el-button
      >
      <el-button class="btn back" @click="handleBack">返回</el-button>
    </div>

    <el-dialog
      :title="'跟进记录'"
      v-model="followshow"
      width="1400px"
      append-to-body
    >
      <Followdetail v-if="followshow" ref="followdetail"></Followdetail>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getEndFollowApi,
  addFollowApi,
  getProjectApi,
} from "@/api/sales/project";
import { updatefollow } from "@/api/sales/marketing.js";
import Followdetail from "./followdetail";
import { ElMessage, ElMessageBox } from "element-plus";
const emit = defineEmits([
  // 刷新父组件表格数据
  "refreshList",
  // 更新跟进组件显隐
  "update:followAddShow",
  //处理编辑
  "handleredit",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 客户表单引用
const followFormRef = ref();
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();

let followshow = ref(false);
//数据
let rowdata = ref({
  projectName: "",
  projectCode: "",
});
// 跟进表单引用
const followFormTemplate = {
  content: "",
  followTime: "",
  nextFollowTime: "",
  projectId: null,
  tableData: [],
};
const data = reactive({
  // 跟进表单
  followForm: JSON.parse(JSON.stringify(followFormTemplate)),
  // 跟进表单校验规则
  queryRules: {
    followTime: [
      { required: true, message: "请选择跟进时间", trigger: "change" },
    ],
    content: [{ required: true, message: "请输入跟进内容", trigger: "blur" }],
    // nextFollowTime: [
    //   { required: true, message: "请选择下次跟进", trigger: "change" },
    // ],
  },
});
const { followForm, queryRules } = toRefs(data);

/**
 * @description: 保存
 * @param {Object} followFormRef 跟进表单引用
 */
const handleAddSave = async (followFormRef) => {
  if (!followFormRef) return;
  await followFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          if (pageedit.value == "edit") {
            let obj = {
              followTime: followForm.value.followTime,
              nextFollowTime: followForm.value.nextFollowTime,
              followId: followForm.value.followId,
              projectId: followForm.value.projectId,
              content: followForm.value.content,
            };
            const res = await updatefollow(obj);
            if (res.code === 200) {
              emit("update:followAddShow", false);
              if (props.pageType == "isfollow") {
                emit("refreshList", rowdata.value);
              } else {
                emit("refreshList", false);
              }
              ElMessage.success(res.msg);
              followForm.value = JSON.parse(JSON.stringify(followFormTemplate));
            } else {
              ElMessage.error(res.msg);
            }
          } else {
            const res = await addFollowApi(followForm.value);
            if (res.code === 200) {
              emit("update:followAddShow", false);
              if (props.pageType == "isfollow") {
                emit("refreshList", rowdata.value);
              } else {
                emit("refreshList", false);
              }
              ElMessage.success(res.msg);
              followForm.value = JSON.parse(JSON.stringify(followFormTemplate));
            } else {
              ElMessage.error(res.msg);
            }
          }
        })
        .catch(() => {});
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      emit("update:followAddShow", false);
      followForm.value = JSON.parse(JSON.stringify(followFormTemplate));
    })
    .catch(() => {});
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (row) => {
  rowdata.value = row;
  console.log("zhixng ", row);
  try {
    console.log("1");
    followForm.value.projectId = row.projectId;
    console.log(2);
    if (props.pageType === "follow" || props.pageType === "isfollow") {
      console.log(3);
      const res = await getEndFollowApi(row.projectId);
      if (res) {
        console.log(4);
        console.log("res");
        followForm.value.followTime = res.createTime;
      }
    } else {
      console.log("2");
      const res = await getProjectApi(row.projectId);
      followForm.value.tableData = res.proFollowUpRecordInfoVos;
    }
  } catch (error) {}
};
/**
 * @description: 处理跟进详情信息
 * @param {Number} id
 */
const followdetail = ref(null);
const handlerdetail = (row) => {
  followshow.value = true;
  setTimeout(() => {
    followdetail.value.handleDetailInfo({ ...row, ...rowdata.value });
  }, 100);
};

/**
 * @description: 处理编辑信息
 * @param {Number} id
 */
const handleredit = (row) => {
  console.log("执行");
  emit("handleredit", { ...row, ...rowdata.value });
};

let pageedit = ref("");
const editInfo = (data) => {
  console.log("编辑", data);
  rowdata.value = data;
  followForm.value = data;
  pageedit.value = "edit";
};

onMounted(() => {
  if (props.pageType !== "detail" && props.pageType !== "check") {
    nextTick(() => {
      setTimeout(() => {
        refInput.value.focus();
      }, 800);
    });
  }
});

defineExpose({
  handleDetailInfo,
  editInfo,
});
</script>
<style lang="scss" scoped>
.followAdd {
  width: 100%;
  height: 100%;
  overflow-y: scroll;

  .content {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .content-title {
      font-size: 20px;
      font-weight: 700;
      flex: 3;
    }
    .content-number {
      display: flex;
      flex: 2;
      align-items: center;
    }
  }
  .follow-info {
    padding: 20px 10px 5px 10px;
    background-color: #f0f0f0;
    margin: 10px 0;
    .custom-textarea {
      :deep(.el-textarea__inner) {
        max-height: 200px !important; /* 你可以根据需要调整这个值 */
      }
    }
  }
  .follow-detail-info {
    margin-top: 20px;
    .table-operate {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #437dfb;
      .line {
        width: 1px;
        height: 20px;
        background-color: #437dfb;
      }
    }
  }
  .allbutton {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
  }
}
:deep(.el-collapse-item__arrow) {
  visibility: hidden;
}
</style>
<style lang="scss">
.followAdd {
  .el-popper.is-dark {
    max-width: 800px !important;
  }
}
</style>
